import { _decorator, Node, Vec2 } from 'cc';
import { MaxHeight } from '../consts';
import { UiBasic } from './basic';
const { ccclass } = _decorator;

@ccclass('Bg')
export class Bg extends UiBasic {
    private speed: number = 0;
    private initPos: Vec2;
    private isInit: boolean = false;
    init(speed: number) {
        if (this.isInit) return;
        this.isInit = true;
        this.speed = speed;
        this.initPos = new Vec2(this.node.position.x, this.node.position.y);
        this.enabled = false;
    }

    public startGame() {
        this.node.setPosition(this.initPos.x, this.initPos.y);
        this.enabled = true;
    }
    protected update(dt: number): void {
        let y = this.node.position.y - this.speed * dt;
        if (y < -(MaxHeight * 1.5)) {
            y = y + MaxHeight * 3;
        }
        this.node.setPosition(this.node.position.x, y);
    }
}

export const addBackgroundEntity = (node: Node, speed: number) => {
    const bg = node.addComponent(Bg);
    bg.init(speed);
};
